package cn.iocoder.yudao.module.reading.service.favorite;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.reading.controller.app.favorite.vo.FavoriteCreateReqVO;
import cn.iocoder.yudao.module.reading.controller.app.favorite.vo.FavoriteRespVO;
import cn.iocoder.yudao.module.reading.controller.app.favorite.vo.FavoriteItemRespVO;
import cn.iocoder.yudao.module.reading.dal.dataobject.audio.AudioResourceDO;
import cn.iocoder.yudao.module.reading.dal.dataobject.book.PictureBookDO;
import cn.iocoder.yudao.module.reading.dal.dataobject.bookset.BookSetDO;
import cn.iocoder.yudao.module.reading.dal.dataobject.favorite.UserFavoriteDO;
import cn.iocoder.yudao.module.reading.dal.mysql.audio.AudioResourceMapper;
import cn.iocoder.yudao.module.reading.dal.mysql.book.PictureBookMapper;
import cn.iocoder.yudao.module.reading.dal.mysql.bookset.BookSetMapper;
import cn.iocoder.yudao.module.reading.dal.mysql.favorite.UserFavoriteMapper;
import cn.iocoder.yudao.module.reading.enums.favorite.FavoriteTypeEnum;
import cn.iocoder.yudao.module.reading.framework.util.StaticResourceUrlUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import jakarta.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.reading.enums.ErrorCodeConstants.*;

/**
 * 收藏管理 Service 实现类
 *
 * @author 李晨
 */
@Service
@Validated
@Slf4j
public class FavoriteServiceImpl implements FavoriteService {

    @Resource
    private UserFavoriteMapper userFavoriteMapper;
    @Resource
    private BookSetMapper bookSetMapper;
    @Resource
    private PictureBookMapper pictureBookMapper;
    @Resource
    private AudioResourceMapper audioResourceMapper;
    @Resource
    private StaticResourceUrlUtils staticResourceUrlUtils;

    @Override
    public Long addFavorite(Long userId, FavoriteCreateReqVO createReqVO) {
        // 验证收藏类型
        FavoriteTypeEnum favoriteType = FavoriteTypeEnum.fromCode(createReqVO.getTargetType());
        if (favoriteType == null) {
            throw exception(FAVORITE_TYPE_INVALID);
        }

        // 验证目标对象是否存在
        validateTargetExists(createReqVO.getTargetType(), createReqVO.getTargetId());

        // 检查是否已收藏
        UserFavoriteDO existingFavorite = userFavoriteMapper.selectByUserIdAndTarget(
                userId, createReqVO.getTargetType(), createReqVO.getTargetId());
        if (existingFavorite != null) {
            throw exception(FAVORITE_ALREADY_EXISTS);
        }

        // 创建收藏记录
        UserFavoriteDO favorite = UserFavoriteDO.builder()
                .userId(userId)
                .favoriteType(createReqVO.getTargetType())
                .targetId(createReqVO.getTargetId())
                .remark(createReqVO.getRemark())
                .build();

        userFavoriteMapper.insert(favorite);
        return favorite.getId();
    }

    @Override
    public void removeFavorite(Long userId, String favoriteType, Long targetId) {
        int deletedCount = userFavoriteMapper.deleteByUserIdAndTarget(userId, favoriteType, targetId);
        if (deletedCount == 0) {
            throw exception(FAVORITE_NOT_EXISTS);
        }
    }

    @Override
    public boolean isFavorited(Long userId, String favoriteType, Long targetId) {
        UserFavoriteDO favorite = userFavoriteMapper.selectByUserIdAndTarget(userId, favoriteType, targetId);
        return favorite != null;
    }

    @Override
    public Map<Long, Boolean> batchCheckFavoriteStatus(Long userId, String favoriteType, List<Long> targetIds) {
        if (CollUtil.isEmpty(targetIds)) {
            return Map.of();
        }

        List<Long> favoritedIds = userFavoriteMapper.selectFavoriteTargetIds(userId, favoriteType, targetIds);
        
        return targetIds.stream().collect(Collectors.toMap(
                targetId -> targetId,
                targetId -> favoritedIds.contains(targetId)
        ));
    }

    @Override
    public List<FavoriteRespVO> getUserFavorites(Long userId, String favoriteType, Integer limit) {
        // 获取收藏记录
        List<UserFavoriteDO> favorites = userFavoriteMapper.selectByUserIdAndType(userId, favoriteType, limit);
        
        if (CollUtil.isEmpty(favorites)) {
            return new ArrayList<>();
        }

        // 构建响应
        return favorites.stream().map(favorite -> {
            FavoriteRespVO respVO = new FavoriteRespVO();
            respVO.setId(favorite.getId());
            respVO.setFavoriteType(favorite.getFavoriteType());
            respVO.setTargetId(favorite.getTargetId());
            respVO.setRemark(favorite.getRemark());
            respVO.setCreateTime(favorite.getCreateTime());

            // 设置目标对象信息
            FavoriteRespVO.FavoriteTargetVO target = buildTargetInfo(favorite.getFavoriteType(), favorite.getTargetId());
            respVO.setTarget(target);

            return respVO;
        }).collect(Collectors.toList());
    }

    @Override
    public Long countUserFavorites(Long userId, String favoriteType) {
        return userFavoriteMapper.countByUserIdAndType(userId, favoriteType);
    }

    @Override
    public void clearUserFavorites(Long userId, String favoriteType) {
        if (favoriteType == null) {
            // 清空所有收藏
            userFavoriteMapper.delete(UserFavoriteDO::getUserId, userId);
        } else {
            // 清空指定类型的收藏
            userFavoriteMapper.deleteByUserIdAndType(userId, favoriteType);
        }
    }

    @Override
    public boolean toggleFavorite(Long userId, String favoriteType, Long targetId, String remark) {
        // 检查当前收藏状态
        boolean isFavorited = isFavorited(userId, favoriteType, targetId);
        
        if (isFavorited) {
            // 如果已收藏，则取消收藏
            removeFavorite(userId, favoriteType, targetId);
            return false;
        } else {
            // 如果未收藏，则添加收藏
            FavoriteCreateReqVO createReqVO = new FavoriteCreateReqVO();
            createReqVO.setTargetType(favoriteType);
            createReqVO.setTargetId(targetId);
            createReqVO.setRemark(remark);
            addFavorite(userId, createReqVO);
            return true;
        }
    }

    /**
     * 验证目标对象是否存在
     */
    private void validateTargetExists(String favoriteType, Long targetId) {
        switch (favoriteType) {
            case "book_set":
                BookSetDO bookSet = bookSetMapper.selectById(targetId);
                if (bookSet == null) {
                    throw exception(BOOK_SET_NOT_EXISTS);
                }
                break;
            case "book":
                PictureBookDO book = pictureBookMapper.selectById(targetId);
                if (book == null) {
                    throw exception(PICTURE_BOOK_NOT_EXISTS);
                }
                break;
            case "audio":
                AudioResourceDO audio = audioResourceMapper.selectById(targetId);
                if (audio == null) {
                    throw exception(AUDIO_RESOURCE_NOT_EXISTS);
                }
                break;
            default:
                throw exception(FAVORITE_TYPE_INVALID);
        }
    }

    /**
     * 构建目标对象信息
     */
    private FavoriteRespVO.FavoriteTargetVO buildTargetInfo(String favoriteType, Long targetId) {
        FavoriteRespVO.FavoriteTargetVO target = new FavoriteRespVO.FavoriteTargetVO();
        
        switch (favoriteType) {
            case "book_set":
                BookSetDO bookSet = bookSetMapper.selectById(targetId);
                if (bookSet != null) {
                    target.setTitle(bookSet.getTitle());
                    target.setCover(staticResourceUrlUtils.toFullUrl(bookSet.getCover()));
                    target.setDescription(bookSet.getDescription());
                    target.setLanguage(bookSet.getLanguage());
                    target.setBookCount(bookSet.getBookCount());
                }
                break;
            case "book":
                PictureBookDO book = pictureBookMapper.selectById(targetId);
                if (book != null) {
                    target.setTitle(book.getTitle());
                    target.setCover(staticResourceUrlUtils.toFullUrl(book.getCover()));
                    // 获取绘本集信息
                    BookSetDO bookSet2 = bookSetMapper.selectById(book.getBookSetId());
                    if (bookSet2 != null) {
                        target.setDescription(bookSet2.getTitle());
                        target.setLanguage(bookSet2.getLanguage());
                    }
                }
                break;
            case "audio":
                AudioResourceDO audio = audioResourceMapper.selectById(targetId);
                if (audio != null) {
                    target.setTitle(audio.getTitle());
                    target.setCover(staticResourceUrlUtils.toFullUrl(audio.getCover()));
                    target.setLanguage(audio.getLanguage());
                    target.setDuration(audio.getDuration());
                }
                break;
        }
        
        return target;
    }

    @Override
    public PageResult<FavoriteRespVO> getUserFavoritesPage(Long userId, String favoriteType, PageParam pageParam) {
        // 分页查询收藏记录
        PageResult<UserFavoriteDO> pageResult = userFavoriteMapper.selectPageByUserIdAndType(userId, favoriteType, pageParam);

        if (CollUtil.isEmpty(pageResult.getList())) {
            return PageResult.empty();
        }

        // 构建响应
        List<FavoriteRespVO> respList = pageResult.getList().stream().map(favorite -> {
            FavoriteRespVO respVO = new FavoriteRespVO();
            respVO.setId(favorite.getId());
            respVO.setFavoriteType(favorite.getFavoriteType());
            respVO.setTargetId(favorite.getTargetId());
            respVO.setRemark(favorite.getRemark());
            respVO.setCreateTime(favorite.getCreateTime());

            // 设置目标对象信息
            FavoriteRespVO.FavoriteTargetVO target = buildTargetInfo(favorite.getFavoriteType(), favorite.getTargetId());
            respVO.setTarget(target);

            return respVO;
        }).collect(Collectors.toList());

        return new PageResult<>(respList, pageResult.getTotal());
    }

    @Override
    public PageResult<FavoriteItemRespVO> getUserFavoriteItemsPage(Long userId, String favoriteType, PageParam pageParam) {
        // 分页查询收藏记录
        PageResult<UserFavoriteDO> pageResult = userFavoriteMapper.selectPageByUserIdAndType(userId, favoriteType, pageParam);

        if (CollUtil.isEmpty(pageResult.getList())) {
            return PageResult.empty();
        }

        // 构建前端友好的响应格式
        List<FavoriteItemRespVO> respList = pageResult.getList().stream().map(favorite -> {
            FavoriteItemRespVO respVO = new FavoriteItemRespVO();
            respVO.setId(favorite.getTargetId()); // 使用目标对象ID作为前端的id
            respVO.setItemType(favorite.getFavoriteType()); // 设置itemType
            respVO.setItemId(favorite.getTargetId()); // 设置itemId（与id相同）
            respVO.setFavoriteType(favorite.getFavoriteType());
            respVO.setRemark(favorite.getRemark());
            respVO.setFavoriteTime(favorite.getCreateTime());

            // 根据收藏类型设置详细信息
            switch (favorite.getFavoriteType()) {
                case "book_set":
                    BookSetDO bookSet = bookSetMapper.selectById(favorite.getTargetId());
                    if (bookSet != null) {
                        respVO.setTitle(bookSet.getTitle());
                        respVO.setCover(staticResourceUrlUtils.toFullUrl(bookSet.getCover()));
                        respVO.setDescription(bookSet.getDescription());
                        respVO.setLanguage(bookSet.getLanguage());
                        respVO.setBookCount(bookSet.getBookCount());
                        // TODO: 设置阅读状态，需要查询用户阅读记录
                        respVO.setReadStatus(false);
                    }
                    break;
                case "book":
                    PictureBookDO book = pictureBookMapper.selectById(favorite.getTargetId());
                    if (book != null) {
                        respVO.setTitle(book.getTitle());
                        respVO.setCover(staticResourceUrlUtils.toFullUrl(book.getCover()));
                        // 获取绘本集信息
                        BookSetDO bookSet2 = bookSetMapper.selectById(book.getBookSetId());
                        if (bookSet2 != null) {
                            respVO.setDescription(bookSet2.getTitle());
                            respVO.setLanguage(bookSet2.getLanguage());
                        }
                        // TODO: 设置阅读状态，需要查询用户阅读记录
                        respVO.setReadStatus(false);
                    }
                    break;
                case "audio":
                    AudioResourceDO audio = audioResourceMapper.selectById(favorite.getTargetId());
                    if (audio != null) {
                        respVO.setTitle(audio.getTitle());
                        respVO.setCover(staticResourceUrlUtils.toFullUrl(audio.getCover()));
                        respVO.setLanguage(audio.getLanguage());
                        respVO.setDuration(audio.getDuration());
                    }
                    break;
            }

            return respVO;
        }).collect(Collectors.toList());

        return new PageResult<>(respList, pageResult.getTotal());
    }

}
